package com.probiz.estoresa.system.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.common.model.system.CompanyInfo;
import com.probiz.estore.common.model.system.SystemConfig;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.system.service.CompanyInfoManager;

public class FootContextController extends
		GenericStoreAdminController<SystemConfig> {
	private CompanyInfoManager companyInfoManager = null;

	public void setCompanyInfoManager(CompanyInfoManager companyInfoManager) {
		this.companyInfoManager = companyInfoManager;
	}

	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		CompanyInfo companyInfo = companyInfoManager.getDefaultCompany();
		if(null == companyInfo){
			request.setAttribute("footContext", "");
		}else{
			request.setAttribute("footContext", companyInfo.getFootContext());
		}
		
		return new ModelAndView("system/footContextList");
	}

	public ModelAndView update(HttpServletRequest request,
			HttpServletResponse response) {
		CompanyInfo companyInfo = companyInfoManager.getDefaultCompany();
		String footContext = request.getParameter("footContextBody");
		if(StringUtils.isNotBlank(footContext) && footContext.equals("&nbsp;")){
			footContext = "";
		}else if(StringUtils.isNotBlank(footContext)){
			String [] temp = footContext.split("<br />");
			if(StringUtils.isBlank(temp[0]) || temp[0].equals("&nbsp;")){
				footContext = "";
			}
		}
		if (companyInfo != null ) {
			companyInfo.setFootContext(footContext);
			companyInfoManager.update(companyInfo);
			
		}else{
			CompanyInfo cpInfo = new CompanyInfo();
			cpInfo.setCompanyName("");
			cpInfo.setFootContext(footContext);
			companyInfoManager.save(cpInfo);
		}
		String message = getMessage("update.footContext.success",
				new Object[] { "成功更新网店底部内容！" });
		saveMessage(request, message);
		return defaultAction(request, response);
	}

	
	
	@Override
	protected String getEntityName(SystemConfig entity) {
		return entity.getConfigKey();
	}


	@Override
	protected void initController() throws Exception {

	}

	@Override
	protected void preSave(HttpServletRequest request, SystemConfig entity,
			BindException errors) {

	}
}
